package com.chj.design.sk;

import java.util.HashMap;

// https://blog.csdn.net/rocketeerli/article/details/82345806
public class Code21_Flyweight {
	public static abstract class Pen {
		// 内部状态
		private int length;
		// 外部状态
		protected final String penType;

		// 享元角色必须接受外部状态，且不能更改。
		public Pen(String penType) {
			this.penType = penType;
		}

		// 根据外部状态做出的操作。
		public abstract void introduce();

		// 内部状态的操作。
		public int getLength() {
			return this.length;
		}

		public void setLength(int length) {
			this.length = length;
		}
	}

	public static class Pencil extends Pen {
		public Pencil(String penType) {
			super(penType);
			System.out.println("生产了一根" + penType + "型号的铅笔");
		}

		@Override
		public void introduce() {
			System.out.println("我是铅笔，我的类型是：" + this.penType);
		}
	}

	public static class FlyweightFactory {
		public static HashMap<String, Pen> pool = new HashMap<>();

		public static Pen getPen(String penType) {
			Pen pen = null;
			if (pool.containsKey(penType)) {
				pen = pool.get(penType);
			} else {
				pen = new Pencil(penType);
				pool.put(penType, pen);
			}
			return pen;
		}
	}

	public static void main(String[] args) {
		Pen pen1 = FlyweightFactory.getPen("HB");
		pen1.introduce();
		Pen pen2 = FlyweightFactory.getPen("2B");
		pen2.introduce();
		Pen pen4 = FlyweightFactory.getPen("4B");
		pen4.introduce();

		Pen pen5 = FlyweightFactory.getPen("2B");
		pen5.introduce();
		Pen pen6 = FlyweightFactory.getPen("4B");
		pen6.introduce();
	}
}
